const router = require('koa-router')()
const Dept = require("../models/deptSchema")
const utils = require("../utils/utils")

router.prefix('/dept')

router.get("/list", async (ctx) => {
  const { deptName } = ctx.request.query;
  const params = {}
  if (deptName) params.deptName = deptName;
  const rootList = await Dept.find(params) || [];
  if (deptName) {
    ctx.body = utils.success(rootList);
  } else {
    const list = utils.getTree(rootList, null, [])
    ctx.body = utils.success(list);
  }
})


router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body;
  let res, info;

  try {
    if (action == "create") {
      res = await Dept.create(params)
      info = "创建成功"
    } else if (action == "edit") {
      params.updateTime = new Date()
      res = await Dept.findByIdAndUpdate(_id, params)
      info = "编辑成功"
    } else {
      await Dept.findByIdAndRemove(_id)
      await Dept.deleteMany({
        parentId: {
          $all: [_id]
        }
      })
      info = "删除成功"
    }
    ctx.body = utils.success({}, info);
  } catch (error) {
    ctx.body = utils.fail({}, error.stack);

  }

})



module.exports = router
